package cn.jdemo.io.util;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 图片拼接
 */
public class Client6 {

    public static void main(String[] args) throws Exception {
        byte[] bytes = joinImages(false, new File("D:/1.jpg"), new File("D:/2.jpg"));
        if (Objects.nonNull(bytes)) {
            FileOutputStream fileOutputStream = new FileOutputStream("D:/showqrcode_join.jpg");
            fileOutputStream.write(bytes);
            // new ByteArrayInputStream(bytes).transferTo(new FileOutputStream(""));
        }
    }

    /**
     * 将多张图片拼接成一张
     *
     * @param horizontal 是否为水平拼接
     * @param files 文件列表
     * @return 拼接后的文件字节数组
     */
    private static byte[] joinImages(boolean horizontal, File... files) throws IOException {
        if (Objects.isNull(files) || files.length == 0) {
            return null;
        }
        List<BufferedImage> imageList = new ArrayList<>();
        for (File file : files) {
            BufferedImage image = ImageIO.read(file);
            imageList.add(image);
        }
        int height = imageList.get(0).getHeight();
        int width = imageList.get(0).getWidth();
        if (horizontal) {
            width = imageList.stream().mapToInt(BufferedImage::getWidth).sum();
        } else {
            height = imageList.stream().mapToInt(BufferedImage::getHeight).sum();
        }
        //创建拼接后的图片画布，参数分别为宽，高，类型，这里我们使用RGB3元色类型
        BufferedImage resultImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics graphics = resultImage.getGraphics();
        int previousWidth = 0;
        int previousHeight = 0;
        for (BufferedImage image : imageList) {
            //向画布上画图片
            graphics.drawImage(image, previousWidth, previousHeight, null);
            if (horizontal) {
                previousWidth += image.getWidth();
            } else {
                previousHeight += image.getHeight();
            }
        }
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        ImageIO.write(resultImage, "jpg", output);
        return output.toByteArray();
    }
}